import router from './router'
import store from './store'
import { getToken } from '@/utils/auth'
import { message } from 'ant-design-vue'
import NProgress from 'nprogress'

// 白名单
const whiteList = ['/login'] // no redirect whitelist

router.beforeEach(async (to, from, next) => {
  NProgress.start()

  //   用户已登录
  const hasToken = getToken()
  if (hasToken) {
    if (to.path === '/login') {
      //   登录状态跳转login 直接返回首页
      next({ path: '/' })
      return NProgress.done()
    }
    // 登录状态下 查看是否有用户信息
    const hasGetUserInfo = store.getters.name
    if (hasGetUserInfo) {
      return next()
    }
    // 没有用户信息 获取
    try {
      await store.dispatch('getUserProfile')
      next()
    } catch (error) {
      await store.dispatch('resetToken')
      message.error(error || 'Has Error')
      next(`/login?redirect=${to.path}`)
      NProgress.done()
    }
  }
  //   用户未登录
  if (whiteList.includes(to.path)) {
    //   前往页面在白名单
    return next()
  } else {
    next(`/login?redirect=${to.path}`)
    NProgress.done()
  }
})
router.afterEach(() => {
  NProgress.done()
})
